package cn.ycxy.lbl.posts.service.impl;

import cn.ycxy.lbl.pojo.posts.domain.LblCsDiscussPost;
import cn.ycxy.lbl.posts.service.IDiscussPostsService;
import cn.ycxy.lbl.posts.service.ILikeService;
import cn.ycxy.lbl.posts.utils.RedisKeyUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class LikeServiceImpl implements ILikeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IDiscussPostsService discussPostsService;

    @Override
    public void like(long userId, int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
        UpdateWrapper<LblCsDiscussPost> wrapper = new UpdateWrapper<>();
        if (isMember) { //移除赞
            redisTemplate.opsForSet().remove(entityLikeKey, userId);
            wrapper.setSql("score = score-1")
                    .eq("id", entityId);
        } else {    //点赞
            redisTemplate.opsForSet().add(entityLikeKey, userId);
            wrapper.setSql("score = score+1")
                    .eq("id", entityId);
        }
        discussPostsService.update(wrapper);
    }

    @Override
    public long findEntityLikeCount(int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }

    @Override
    public int findEntityLikeStatus(long userId, int entityType, int entityId) {
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
    }

    @Override
    public void recordEntityWatch(long userId, int entityType, int entityId) {
        String watchKey = RedisKeyUtil.getEntityWatchKey(entityType, entityId);
        redisTemplate.opsForSet().add(watchKey, userId);
    }

    @Override
    public void recordEntityWant(long userId, int entityType, int entityId) {
        String wantKey = RedisKeyUtil.getEntityWantKey(entityType, entityId);
        redisTemplate.opsForSet().add(wantKey, userId);
    }

    @Override
    public long findEntityWatchCount(int entityType, int entityId) {
        String watchKey = RedisKeyUtil.getEntityWatchKey(entityType, entityId);
        return redisTemplate.opsForSet().size(watchKey);
    }

    @Override
    public long findEntityWantCount(int entityType, int entityId) {
        String wantKey = RedisKeyUtil.getEntityWantKey(entityType, entityId);
        return redisTemplate.opsForSet().size(wantKey);
    }
}
